#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
#include <QDateTime>
#include <QGraphicsOpacityEffect>
#include "viewglobal.h"
#include "../control/mainwindowcontroller.h"
#include "../control/callcontroller.h"
#include "../control/keyboardcontroller.h"
#include "../control/indexpagecontroller.h"
#include "../control/msgpagecontroller.h"
#include "../control/pwdpagecontroller.h"
#include "indexpage.h"
#include "waitingpage.h"
#include "meetcontrolpage.h"
#include "advancesettingpage.h"
#include "basesettingpage.h"
#include "callcontrolpanel.h"
#include "keyboard.h"
#include "messagedialog.h"
#include "passwordinput.h"
#include <QPropertyAnimation>
#include "../sys/sysconfighandler.h"
#include "mainwindowworker.h"
#include "../remoteservice/devicestatusinfo.h"
#include "../remoteservice/platfromstatusinfo.h"
#include "../remoteservice/productinfo.h"
#include "../remoteservice/networkinfo.h"
#include "../model/osdremoteservicemodel.h"
#include "../model/osdutilsmodel.h"
#include "../sys/remotecontrolhandler.h"
#include "../event/standbyevent.h"
#include "../event/returnevent.h"
#include <QBrush>


#define UPDATE_PER_SECONDS  (60)
#define MEMINFO_PER_SECONDS  (20)

#define QRCODE_PATH         QString("/opt/local/web/qrcode.png")

MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_second_count(1),
    curState(1)
{
	ui->setupUi(this);
	setAutoFillBackground(false);
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
#ifdef __linux
    //qws 服务的背景板，设置为透明
    QWSServer::instance()->setBackground(QBrush(QColor(143,2,26,0)));
#endif

    worker = new MainWindowWorker;
    connect(this, SIGNAL(updateStatus()), worker, SLOT(work()));

    init();

    connect(&m_timer, SIGNAL(timeout()), this, SLOT(timerHandle()));
    timerHandle();
    m_timer.start(1000);

    //启动键盘监听线程
    RemoteControlHandler::instance().init();

    qApp->installEventFilter(this);

    connect(&MainWindowController::instance(),SIGNAL(changeTopPageSig(int)),this,SLOT(changeTopPageSlot(int)));
    connect(&MainWindowController::instance(),SIGNAL(changeSubPageSig(int)),this,SLOT(changeSubPageSlot(int)));

    connect(&MainWindowController::instance(),SIGNAL(updateIPSig(QString)),this,SLOT(updateIP(QString)));
    connect(&MainWindowController::instance(),SIGNAL(updateStatusSig()),this,SIGNAL(updateStatus()));
    connect(&MainWindowController::instance(),SIGNAL(changeBackgroundSig(QString)),this,SLOT(backgroundProperty(QString)));
    connect(&KeyBoardController::instance(), SIGNAL(showSig(QObject*, int)), this, SLOT(showKeyBoard(QObject *,int)));
    connect(&KeyBoardController::instance(), SIGNAL(hideSig()), this, SLOT(hideKeyBoard()));
    connect(&MsgPageController::instance(), SIGNAL(showMsgSig(QString)), this, SLOT(showMsg(QString)));
    connect(&PwdPageController::instance(), SIGNAL(inputPwdSig(QString, QString)), this, SLOT(showPwdInput(QString, QString)));

    connect(&OSDRemoteServiceModel::instance(), SIGNAL(notifyLeaveConf()), this, SLOT(leaveConf()));
    connect(&OSDRemoteServiceModel::instance(), SIGNAL(notifyEnterInConf()), this, SLOT(enterConf()));
    connect(&OSDRemoteServiceModel::instance(), SIGNAL(notifyExitApp()), this, SLOT(exitApp()));

//    connect(&OSDRemoteServiceModel::instance(),
//            SIGNAL(notifyDeviceUsingStatus(DeviceStatusInfo)),
//            this, SLOT(deviceInfoSlot(DeviceStatusInfo)));
        connect(&OSDRemoteServiceModel::instance(),
                SIGNAL(notifySvcRegisterStatus(SVCStatusInfo)),
                this, SLOT(svcInfoSlot(SVCStatusInfo)));
    connect(&OSDRemoteServiceModel::instance(),
            SIGNAL(notifyDeviceRegisterStatus(PlatfromStatusInfo)),
            this, SLOT(platformInfoSlot(PlatfromStatusInfo)));
    connect(&OSDRemoteServiceModel::instance(),
            SIGNAL(notifyProductInfo(ProductInfo)),
            this, SLOT(productInfoSlot(ProductInfo)));
    connect(&OSDRemoteServiceModel::instance(),
            SIGNAL(notifyNetworkStatus(NetworkInfo)),
            this, SLOT(networkInfoSlot(NetworkInfo)));

    changeTopPageSlot(OSD::ViewGlobal::TOP_PAGE_MAIN_WINDOW);
    emit updateStatus();    //初始化结束后，直接启动线程
}

MainWindow::~MainWindow()
{
    OSDRemoteServiceModel::instance().quit();
    RemoteControlHandler::instance().quit();
    workThread.quit();
    workThread.wait();
    delete m_keyboard;
    delete ui;
    delete worker;
    delete m_pwdpage;
    delete m_msgpage;
    delete m_waitpage;
}

void MainWindow::exitApp()
{
    //QApplication::exit(0);
}

void MainWindow::leaveConf()
{
    IndexPageController::instance().resetUi();
    changeTopPageSlot(OSD::ViewGlobal::TOP_PAGE_MAIN_WINDOW);
}

void MainWindow::enterConf()
{
    changeSubPageSlot(OSD::ViewGlobal::SUB_PAGE_MEET_LOADING);
}

void MainWindow::init()
{
    m_pwdpage = new PasswordInput/*(this)*/;
    m_msgpage = new MessageDialog/*(this)*/;

    m_indexpage = new IndexPage(this);
    m_waitpage = new WaitingPage;
    m_meetpage = new MeetControlPage(this);
    AdvanceSettingPage *advancepage = new AdvanceSettingPage(this);
    m_basepage = new BaseSettingPage(this);
    ui->stackedWidget->insertWidget(OSD::ViewGlobal::SUB_PAGE_INDEX,m_indexpage);
    ui->stackedWidget->insertWidget(OSD::ViewGlobal::SUB_PAGE_BASE_CONFIG,m_basepage);
    ui->stackedWidget->insertWidget(OSD::ViewGlobal::SUB_PAGE_ADVANCE_CONFIG,advancepage);
    ui->stackedWidget->setCurrentIndex(0);
    ui->stackedWidget->setContentsMargins(0,0,0,0);
    m_waitpage->hide();

    ui->main_stackedWidget->insertWidget(1,m_meetpage);

    m_keyboard = new KeyBoard(this);

    m_keyboard->setGeometry(this->x(),
                            this->y()+this->height(),
                            m_keyboard->width(),m_keyboard->height());

    m_keyboardAnimation = new QPropertyAnimation(m_keyboard,"geometry",this);
    m_keyboardAnimation->setEasingCurve(QEasingCurve::InOutQuad);
    m_keyboardAnimation->setDuration(500);

    ui->lblBluetoothStatus->hide();
    ui->lblHotpointStatus->hide();
    ui->lblWifiStatus->hide();
    m_pwdpage->hide();
    m_msgpage->hide();

//#ifdef __linux
//显示二维码
//ui->lblQRCode->setPixmap(QPixmap(QRCODE_PATH));
//ui->lblQRCode->setScaledContents(true);
//#endif

}

void MainWindow::changeTopPageSlot(int page)
{
    if (page == OSD::ViewGlobal::TOP_PAGE_MAIN_WINDOW)
    {
        changeSubPageSlot(OSD::ViewGlobal::SUB_PAGE_INDEX);
    }
    {
        m_waitpage->hide();
    }
    ui->main_stackedWidget->setCurrentIndex(page);
}

void MainWindow::changeSubPageSlot(int page)
{
    if (m_msgpage->isVisible())
    {
        m_msgpage->hide();
    }

    if (m_pwdpage->isVisible())
    {
        m_pwdpage->hide();
    }

    if (page == OSD::ViewGlobal::SUB_PAGE_MEET_LOADING)
    {
        m_waitpage->show();
        return;
    }
    else
    {
        if (m_waitpage->isVisible())
        {
            m_waitpage->hide();
        }
    }

    backgroundProperty("0");

    ui->stackedWidget->setCurrentIndex(page);
}

void MainWindow::backgroundProperty(QString value)
{
    if (ui->backwidget->property("baseconfig").toString() != value)
    {
        ui->backwidget->setProperty("baseconfig",value);
        ui->backwidget->style()->unpolish(ui->backwidget);
        ui->backwidget->style()->polish(ui->backwidget);
        ui->backwidget->update();
    }
}

void MainWindow::showKeyBoard(QObject *o,int type)
{
    if(m_keyboard->y() >= this->height())
    {
        m_keyboard->setShowKeyBoard(o, type);
        m_keyboardAnimation->setStartValue(QRect(m_keyboard->x(), m_keyboard->y(), m_keyboard->width(), m_keyboard->height()));
        m_keyboardAnimation->setEndValue(QRect(m_keyboard->x(), m_keyboard->y()-m_keyboard->height(), m_keyboard->width(), m_keyboard->height()));
        m_keyboardAnimation->start();
    }
}

void MainWindow::hideKeyBoard()
{
    if(m_keyboard->y() < this->height())
    {
        m_keyboardAnimation->setStartValue(QRect(m_keyboard->x(), m_keyboard->y(),m_keyboard->width(), m_keyboard->height()));
        m_keyboardAnimation->setEndValue(QRect(m_keyboard->x(), m_keyboard->y()+m_keyboard->height(), m_keyboard->width(), m_keyboard->height()));
        m_keyboardAnimation->start();
    }
}

void MainWindow::timerHandle()
{
    if (m_second_count >= UPDATE_PER_SECONDS)
    {   //到达1分钟，刷新界面状态
        m_second_count = 1;
        emit updateStatus();
    }
    else
    {
        m_second_count += 1;
    }
}

void MainWindow::paintEvent(QPaintEvent *e) {
    QPainter p(this);
    //if (m_call_status > 0) {
        p.setCompositionMode(QPainter::CompositionMode_Clear);
        p.fillRect(0, 0, 1920, 1080, Qt::SolidPattern);
    //}
    e = e;

//    QStyleOption opt;
//    opt.initFrom(this);
//    QPainter p(this);
//    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);//绘制样式
}

bool MainWindow::eventFilter(QObject* o, QEvent* e)
{

    if(e->type() == ReturnEvent::eventType)
    {
        if (m_meetpage->isVisible())
        {
            //leave conf
//            OSDRemoteServiceModel::instance().leaveConference();
//            IndexPageController::instance().resetUi();
            return true;
        }
        changeTopPageSlot(OSD::ViewGlobal::TOP_PAGE_MAIN_WINDOW);
        return true;
    }
    else if (e->type() == StandbyEvent::eventType)
    {
        if(curState == 1)
        {
            OSDRemoteServiceModel::instance().standby();
            curState = 0;
        }
        else
        {
            OSDRemoteServiceModel::instance().recover();
            curState = 1;
        }
        return true;
    }
	return QWidget::eventFilter(o, e);
}

void MainWindow::updateDeviceStatus(int v)
{
    //设备状态
}

void MainWindow::updateDeviceName(QString name)
{
    ui->lblDeviceName->setText(name);
    SysConfigHandler::instance().setDeviceName(name);
}

void MainWindow::updateIP(QString ip)
{
    ui->lblLocalIP->setText(ip);
}

void MainWindow::updateNetStatus(bool active)
{
    if (active)
    {
        ui->lblNetStatus->setProperty("connected","1");
    }
    else
    {
        ui->lblNetStatus->setProperty("connected","0");
    }

    ui->lblNetStatus->style()->unpolish(ui->lblNetStatus);
    ui->lblNetStatus->style()->polish(ui->lblNetStatus);
    ui->lblNetStatus->update();
    SysConfigHandler::instance().setActive(active);
}

void MainWindow::updateSVCRegistered(int v)
{
    QString s="";
    if (v == SVCStatusInfo::NO_REGISTER)
    {
        s = "未注册";
        ui->widCloudVedio->setProperty("register","0");
    }
    else if (v == SVCStatusInfo::REGISTERED)
    {
        s = "注册成功";
        ui->widCloudVedio->setProperty("register","2");
    }
    else
    {
        s = "注册失败";
        ui->widCloudVedio->setProperty("register","1");
    }
//    ui->lblPlatformStatus->setText(s);
    ui->widCloudVedio->style()->unpolish(ui->widCloudVedio);
    ui->widCloudVedio->style()->polish(ui->widCloudVedio);
    ui->widCloudVedio->update();
//    SysConfigHandler::instance().setRegistered(v);
}

void MainWindow::updateRegistered(int v)
{
    QString s="";
    if (v == PlatfromStatusInfo::NO_REGISTER)
    {
        s = "未注册";
        ui->widPlatformStatusLogo->setProperty("register","0");
    }
    else if (v == PlatfromStatusInfo::REGISTERED)
    {
        s = "注册成功";
        ui->widPlatformStatusLogo->setProperty("register","2");
    }
    else
    {
        s = "注册失败";
        ui->widPlatformStatusLogo->setProperty("register","1");
    }
//    ui->lblPlatformStatus->setText(s);
    ui->widPlatformStatusLogo->style()->unpolish(ui->widPlatformStatusLogo);
    ui->widPlatformStatusLogo->style()->polish(ui->widPlatformStatusLogo);
    ui->widPlatformStatusLogo->update();
    SysConfigHandler::instance().setRegistered(v);
}

void MainWindow::deviceInfoSlot(DeviceStatusInfo info)
{
    if (info.getIsSuccess())
    {
        updateDeviceStatus(info.getDeviceStatus());
    }
}

void MainWindow::svcInfoSlot(SVCStatusInfo info)
{
    if (info.getIsSuccess())
    {
        updateSVCRegistered(info.getSvcStatus());
    }
}

void MainWindow::platformInfoSlot(PlatfromStatusInfo info)
{
    if (info.getIsSuccess())
    {
        updateRegistered(info.getPlatformStatus());
    }
}
void MainWindow::productInfoSlot(ProductInfo info)
{
    if (info.getIsSuccess())
    {
        updateDeviceName(info.getName());
        //ui->lblSN->setText(info.getSn());
        SysConfigHandler::instance().setVersion(info.getTerminalVersion());
    }
}
void MainWindow::networkInfoSlot(NetworkInfo info)
{
    if (info.getIsSuccess())
    {
        updateIP(info.getIp());
        updateNetStatus(info.getActive());
    }
}

void MainWindow::showMsg(QString str)
{
    m_msgpage->setTxt(str);
    m_msgpage->show();
}

void MainWindow::showPwdInput(QString num, QString name)
{
    m_pwdpage->setConferenceParam(num,name);
    m_pwdpage->showMaximized();
}

void MainWindow::showEvent(QShowEvent *e)
{
    QMainWindow::showEvent(e);
}

void MainWindow::loadSchedule()
{
    m_indexpage->loadSchedule();
}
